// func参数this指向Window
function debounce(func, wait, immediate) {
  let timeout, result
  let debounced = function () {
    // console.log(arguments);
    // 改变执行函数 func 内部this的指向
    let context = this
    // 要传递event事件
    let args = arguments
    clearTimeout(timeout)
    if (immediate) {
      let flag = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (flag)
        result = func.apply(context, args)
    } else {
      timeout = setTimeout(() => {
        func.apply(context, args)
      }, wait)
    }
    return result
  }
  debounced.cancel = function () {
    clearTimeout(timeout)
    timeout = null
  }
  return debounced
}